package com.lvideo.component.extraplayer.videoview;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.ViewGroup;

import com.fun.ad.FSAdPlayer;
import com.fun.xm.ExtraCPInfo;
import com.fun.xm.FSCallback;
import com.fun.xm.FSIVideoPlayer;
import com.fun.xm.FSPlayer;
import com.funshion.player.AdsPlayListener;
import com.funshion.player.IMediaPlayer;
import com.funshion.video.entity.FSMediaEpisodeEntity;
import com.funshion.video.util.FSError;
import com.letv.sdk.callbacks.LetvPlayerView;
import com.lvideo.component.extraplayer.Interface.MyAdStatusListener;
import com.lvideo.component.extraplayer.LVideoMediaPlayerControl;
import com.media.ffmpeg.FFMpegPlayer;
import com.novaplayer.videoview.VideoViewH264mp4;
import com.tencent.qqlive.mediaplayer.api.TVK_PlayerVideoInfo;
import com.tencent.qqlive.mediaplayer.api.TVK_UserInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * @author wangtao
 * @version 1.0
 */

public class VideoViewFunshionProxy extends VideoViewH264mp4 implements LVideoMediaPlayerControl {
    private FSAdPlayer fsAdPlayerView;
    private FSIVideoPlayer fsiVideoPlayer;
    private Callback callback;
    private String videoUrl;
    private boolean isAdEnd;
    private List<Integer> definitions = new ArrayList<Integer>();
    private int currentDefinition;
    private String pOrder;
    private IMediaPlayer fsAdPlayer = new IMediaPlayer() {
        private OnErrorListener mErrorListener;
        private MediaPlayer mMediaPlayer = new MediaPlayer();
        private IMediaPlayer.OnPreparedListener mPreparedListener;

        private MediaPlayer.OnErrorListener mInnerErrorListener = new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (mErrorListener != null) {
                    return mErrorListener.onError(fsAdPlayer, what, extra);
                }
                return false;
            }
        };

        private MediaPlayer.OnPreparedListener mInnerPreparedListener = new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                if (mPreparedListener != null) {
                    mPreparedListener.onPrepared(fsAdPlayer);
                }
            }

        };

        @Override
        public int getCurrentPosition() {
            return this.mMediaPlayer.getCurrentPosition();
        }

        @Override
        public int getVideoHeight() {
            return this.mMediaPlayer.getVideoHeight();
        }

        @Override
        public int getVideoWidth() {
            return this.mMediaPlayer.getVideoWidth();
        }

        @Override
        public boolean isPlaying() {
            return this.mMediaPlayer.isPlaying();
        }

        @Override
        public void pause() throws IllegalStateException {
            this.mMediaPlayer.pause();
        }

        @Override
        public void prepareAsync() throws IllegalStateException {
            this.mMediaPlayer.prepareAsync();
        }

        @Override
        public void release() {
            this.mMediaPlayer.release();
        }

        @Override
        public void reset() {
            this.mMediaPlayer.reset();
        }

        @Override
        public void seekTo(int ms) throws IllegalStateException {
            this.mMediaPlayer.seekTo(ms);
        }

        @Override
        public void setDataSource(String arg0) throws IOException,
                IllegalArgumentException, SecurityException, IllegalStateException {
            this.mMediaPlayer.setDataSource(arg0);
        }

        @Override
        public void setDisplay(SurfaceHolder sh) {
            this.mMediaPlayer.setDisplay(sh);
        }

        @Override
        public void setOnErrorListener(OnErrorListener listener) {
            this.mErrorListener = listener;
            if (this.mErrorListener != null) {
                this.mMediaPlayer.setOnErrorListener(this.mInnerErrorListener);
            } else {
                this.mMediaPlayer.setOnErrorListener(null);
            }
        }

        @Override
        public void setOnPreparedListener(IMediaPlayer.OnPreparedListener listener) {
            this.mPreparedListener = listener;
            if (this.mPreparedListener != null) {
                this.mMediaPlayer.setOnPreparedListener(this.mInnerPreparedListener);
            } else {
                this.mMediaPlayer.setOnPreparedListener(null);
            }
        }

        @Override
        public void start() throws IllegalStateException {
            this.mMediaPlayer.start();
        }

        @Override
        public void stop() throws IllegalStateException {
            this.mMediaPlayer.stop();
        }
    };
    private MediaPlayer.OnPreparedListener onPreparedListener;
    private MediaPlayer.OnErrorListener onErrorListener;

    public VideoViewFunshionProxy(Context context) {
        this(context, null);
    }

    public VideoViewFunshionProxy(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoViewFunshionProxy(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private static int convertDefinitionToInt(FSMediaEpisodeEntity.Definition definition) {
        String code = definition.getCode();
        if ("tv".equalsIgnoreCase(code)) {
            return 1;
        } else if ("dvd".equalsIgnoreCase(code)) {
            return 2;
        } else if ("hd".equalsIgnoreCase(code)) {
            return 3;
        } else if ("sdvd".equalsIgnoreCase(code)) {
            return 4;
        }
        return -1;
    }

    private void init() {
        try {
            fsiVideoPlayer = FSPlayer.create(getContext(), null, new FSCallback() {
                @Override
                public int onFailed(FSError fsError) {
                    callback.onFailed(fsError);
                    return 0;
                }

                @Override
                public void onDefinition(List<FSMediaEpisodeEntity.Definition> list, FSMediaEpisodeEntity.Definition definition) {
                    definitions.clear();
                    int i;
                    for (FSMediaEpisodeEntity.Definition d : list) {
                        i = convertDefinitionToInt(d);
                        if (i != -1) {
                            definitions.add(i);
                        }
                    }
                    currentDefinition = convertDefinitionToInt(definition);
                    callback.onDefinition(definitions, currentDefinition);
                }

                @Override
                public void onReceiveUrl(String s) {
                    videoUrl = s;
                    if (isAdEnd) {
                        callback.startPlay(videoUrl);
                    }
                }
            });
            fsiVideoPlayer.setAdsPlayListener(new AdsPlayListener() {
                @Override
                public void onAdsDuration(int i) {
                }

                @Override
                public void onAdsPlayEnd() {
                    isAdEnd = true;
                    callback.onAdEnd();
                    if (videoUrl != null) {
                        callback.startPlay(videoUrl);
                    }
                }

                @Override
                public void onAdsPlayStart() {
                    isAdEnd = false;
                    callback.onAdStart();
                }

                @Override
                public void onAdsTimeUpdate(int i) {
                }
            });
            super.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    fsiVideoPlayer.onMediaPlayerPrepared();
                    onPreparedListener.onPrepared(mp);
                }
            });
            super.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    fsiVideoPlayer.onMediaPlayerError(what, extra);
                    onErrorListener.onError(mp, what, extra);
                    return true;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setupView(ViewGroup viewGroup) {
        if (fsAdPlayerView != null) {
            viewGroup.removeView(fsAdPlayerView);
        }
        fsAdPlayerView = new FSAdPlayer(getContext(), fsAdPlayer);
        viewGroup.addView(fsAdPlayerView, MATCH_PARENT, MATCH_PARENT);
    }

    public void removeAdPlayerView(ViewGroup viewGroup) {
        if (fsAdPlayerView != null) {
            viewGroup.removeView(fsAdPlayerView);
        }
    }


    public void requestAndPrepare(String porder,String vid,String token,String mediaName,String mediaType,int time) {
        if (videoUrl != null && pOrder != null && pOrder.equals(porder)) {
            callback.startPlay(videoUrl);
        } else {
            //构建合作商数据集合
            ExtraCPInfo cpinfo = new ExtraCPInfo();
            cpinfo.setCp("sdkjswh");//CP(合作商ID -风行提供)
            cpinfo.setAccess_token(token);//accessToken(由TokenUtil.getAccessToken获取)
            cpinfo.setOuid("OuidTestAndroid");//用户的唯一标示

            //这里构建假数据,正常使用应该是服务器返回的数据
            JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put("vid", vid);
                jsonObj.put("epnum", porder);
                jsonObj.put("medianame", mediaName);
                jsonObj.put("mediatype", mediaType);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            pOrder = porder;
            isAdEnd = false;
            fsiVideoPlayer.requestAndPrepare(jsonObj.toString(), 2, cpinfo, fsAdPlayerView);
            fsiVideoPlayer.onSeek(time);
        }
    }

    @Override
    public List<Integer> getSupportDefinitions() {
        return null;
    }

    @Override
    public void changeDefinition(int definition) {
        fsiVideoPlayer.changeDefinition(definition);
    }

    @Override
    public int getCurrentDefinition() {
        return currentDefinition;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    public void pause() {
        super.pause();
    }

    @Override
    public void seekTo(int msec) {
        super.seekTo(msec);
        fsiVideoPlayer.onSeek(msec);
    }

    @Override
    public void setOnErrorListener(MediaPlayer.OnErrorListener l) {
        onErrorListener = l;
    }

    @Override
    public void setOnAdNumberListener(FFMpegPlayer.OnAdNumberListener l) {

    }

    @Override
    public void setOnBlockListener(FFMpegPlayer.OnBlockListener l) {

    }

    @Override
    public void setOnHardDecodeErrorListener(FFMpegPlayer.OnHardDecodeErrorListner l) {

    }

    @Override
    public boolean isEnforcementWait() {
        return false;
    }

    @Override
    public void setEnforcementWait(boolean enforcementWait) {

    }

    @Override
    public boolean isEnforcementPause() {
        return false;
    }

    @Override
    public void setEnforcementPause(boolean enforcementPause) {

    }

    @Override
    public void setCacheSize(int video_size, int audio_size, int picutureSize, int startpic_size) {

    }

    @Override
    public boolean isSohuAdvertInPlayback() {
        return false;
    }

    @Override
    public void next() {

    }

    @Override
    public void playVideoAt(int index) {

    }

    @Override
    public void setTencentData(TVK_UserInfo userinfo, TVK_PlayerVideoInfo playerinfo, int currPlayTime) {

    }

    @Override
    public void setLetvScreenView(LetvPlayerView letvScreenView) {

    }

    @Override
    public void setLetvData(long vid, int currPlayTime) {

    }

    @Override
    public void setBestvData(String vid, String fdnCode, long currPlayTime) {

    }

    @Override
    public int getFirstErrorCode() {
        return 0;
    }

    @Override
    public void setOnAdListener(MyAdStatusListener var) {

    }

    @Override
    public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
        onPreparedListener = l;
    }

    public void onActivityPause() {
        fsiVideoPlayer.onActivityPause();
        fsAdPlayerView.onPause();
    }

    public void onActivityResume() {
        fsiVideoPlayer.onActivityResume();
        fsAdPlayerView.onResume();
    }

    public void onActivityDestroy() {
        fsiVideoPlayer.onActivityDestroy();
//        fsAdPlayerView.destroy();
    }

    public interface Callback {
        void startPlay(String url);

        void onAdStart();

        void onAdEnd();

        void onFailed(FSError error);

        void onDefinition(List<Integer> definitions, int curDefinition);
    }

    @Override
    public void onDestroyData() {
        fsAdPlayerView = null;
        fsiVideoPlayer = null;
    }
}
